<script setup>
	import { PlusOutlined } from '@ant-design/icons-vue'
	const props = defineProps({
		answer: {
			type: String,
			required: true
		}
	})
	const answerLocal = ref({
		norm: '',
		keyword: [
			{ key: '得3分', value: 0.3 },
			{ key: '得2分', value: 0.4 }
		]
	})
	// 定义 emit
	const emit = defineEmits(['updateAnswer', 'updateIssueOption'])

	const removeIssueOption = (index) => {
		answerLocal.value.keyword.splice(index, 1)
	}
	const addIssueOption = () => {
		answerLocal.value.keyword.push({ key: '', value: 0 })
	}

	watch(
		() => answerLocal,
		(newVal) => {
			emit('updateIssueOption', '')
			emit('updateAnswer', JSON.stringify(newVal.value))
		},
		{ deep: true }
	)

	// 模拟 created 生命周期
	onBeforeMount(() => {
		try {
			const data = JSON.parse(props.answer)
			if (typeof data === 'object' && data !== null && !Array.isArray(data)) {
				if (data.norm && Array.isArray(data.keyword)) {
					answerLocal.value = data
				}
			}
		} catch (e) {
			/* empty */
		}
	})
</script>

<template>
	<a-form-item>
		<a-row :gutter="16" justify="space-around" align="middle">
			<a-col :span="2"> 标准答案： </a-col>
			<a-col :span="20">
				<a-textarea
					v-model:value="answerLocal.norm"
					placeholder="请输入标准答案"
					:auto-size="{ minRows: 3, maxRows: 5 }"
				/>
			</a-col>
		</a-row>
	</a-form-item>
	<a-form-item>
		<a-row :gutter="16" justify="space-around" align="middle">
			<a-col :span="2"> 关键词： </a-col>
			<a-col :span="20">
				<a-form-item v-for="(option, index) in answerLocal.keyword" :key="index">
					<a-row :gutter="16" justify="space-around" align="middle">
						<a-col :span="16">
							<a-input v-model:value="option.key" placeholder="请输入关键词" />
						</a-col>
						<a-col :span="4">
							<a-space> 占比<a-input-number v-model:value="option.value" :min="0" :max="1" :step="0.1" /> </a-space>
						</a-col>
						<a-col :span="4">
							<a-button danger @click="removeIssueOption(index)">删除</a-button>
						</a-col>
					</a-row>
				</a-form-item>
			</a-col>
		</a-row>
	</a-form-item>
	<a-form-item :wrapper-col="{ offset: 3, span: 20 }">
		<a-button type="dashed" block @click="addIssueOption">
			<PlusOutlined />
			添加关键字
		</a-button>
	</a-form-item>
</template>

<style scoped lang="less"></style>
